import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;


public class LoginMenu extends ScreenManager{

	private static final long serialVersionUID = 1L;
	private EventListenerList listenerList = new EventListenerList();
	private ImageIcon logo;
	private JLabel logoLabel;
	
	public LoginMenu(){
		firePlayerEvent(new SoundManager( this, "playMp3",  "bgm2.mp3" ));
		JPanel loginMenu = new JPanel();
		//loginMenu.setBackground(Color.white);
		
		logo = new ImageIcon(getClass().getResource("bgs/logo.png"));
		logoLabel = new JLabel();
		logoLabel.setIcon(logo);
		loginMenu.add(logoLabel);
		logoLabel.setBounds(110, -195, 500,500);

		getContentPane().add(loginMenu);
		
		loginMenu.setLayout(null);
		
		ImageIcon loginBg = new ImageIcon(getClass().getResource("bgs/loginBg.jpg")); 
		ImageIcon createBg = new ImageIcon(getClass().getResource("bgs/createBg.jpg")); 
		ImageIcon exitBg = new ImageIcon(getClass().getResource("bgs/exitBg.jpg")); 
		ImageIcon changeBg = new ImageIcon(getClass().getResource("bgs/changeBg.jpg")); 
		
		final JTextField userNameTextBox = new JTextField();
		userNameTextBox.setBounds(97,115,70,30);
		loginMenu.add(userNameTextBox);
		final JPasswordField userPasswordTextBox = new JPasswordField();
		userPasswordTextBox.setBounds(257,115,70,30);
		loginMenu.add(userPasswordTextBox);
		
		JLabel userNameLabel = new JLabel("Username");
		JLabel userPasswordLabel = new JLabel("Password");
		
		userNameLabel.setBounds(25, 115, 70, 30);
		userPasswordLabel.setBounds(185, 115, 70, 30);
		
		loginMenu.add(userNameLabel);
		loginMenu.add(userPasswordLabel);
		
		JButton loginButton = new JButton("Log in", loginBg);
		loginButton.addActionListener( new ActionListener()
		{
		    @SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e)
		    {
		    	login(userNameTextBox.getText(), userPasswordTextBox.getText());
		    }
		});
		
		JButton createAccButton = new JButton("Create Account", createBg);
		createAccButton.addActionListener( new ActionListener()
		{
		    @SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e)
		    {
		    	createAcct(userNameTextBox.getText(), userPasswordTextBox.getText());
		    }
		});
		
		JButton changePassButton = new JButton("Change Password", changeBg);
		changePassButton.addActionListener( new ActionListener()
		{
		    @SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e)
		    {
		    	changePass(userNameTextBox.getText(), userPasswordTextBox.getText());
		    }
		});
		JButton exitButton = new JButton("Exit", exitBg);
		exitButton.addActionListener( new ActionListener()
		{
		    public void actionPerformed(ActionEvent e)
		    {
		    	System.exit(0);
		    }
		});
		
		exitButton.setBounds(150, 255, 95, 55);
		loginMenu.add(exitButton);
		
		loginButton.setBounds(150, 175, 95, 55);
		loginMenu.add(loginButton);
		
		createAccButton.setBounds(30, 255, 95, 55);
		loginMenu.add(createAccButton);
		
		changePassButton.setBounds(275, 255, 95, 55);
		loginMenu.add(changePassButton);
	}
	private void login(String name, String password){
		DatabaseManager.openConnection();
		Statement stmt = null;
		boolean user = false;
		boolean isExist = false;
		try {
			String sql = "select * from users";
			stmt = DatabaseManager.conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()){
				if(rs.getString("userName").equals(name)){
					if(rs.getString("userPassword").equals(password)){
						isExist = true;
						break;
					}
					else{
						JOptionPane.showMessageDialog(this, "Incorrect Password!", "ERROR", JOptionPane.ERROR_MESSAGE);
						user = true;
					}
				}
			}
			if(isExist){
				sql = "select * from flappybirdv2db.songpath where userName = '"+name+"' order by dateadded desc limit 1";
				stmt = DatabaseManager.conn.createStatement();
				rs = stmt.executeQuery(sql);
				String songName= "";
				while(rs.next()){
					songName = rs.getString("songPath");
				}
				if(!songName.equals(""))
					firePlayerEvent(new SoundManager( this, "playMp3",  songName ));
				this.dispatchEvent(new WindowEvent(this,WindowEvent.WINDOW_CLOSING));
				MainMenu newFrame = new MainMenu(name);
				newFrame.setVisible(true);
			}
			else{
				if(!user)
					JOptionPane.showMessageDialog(this, "User is not found! Try to Create an Account", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			rs.close();
			DatabaseManager.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void createAcct(String name, String password){
		DatabaseManager.openConnection();
		Statement stmt = null;
		boolean isExist = false;
		try {
			String sql = "select * from users";
			stmt = DatabaseManager.conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()){
				if(rs.getString("userName").equals(name)){
					isExist = true;
					break;
				}
			}
			rs.close();
			if(!isExist){
				sql = "insert into flappybirdv2db.users(userName, userPassword) values (\"" + name + "\",\"" + password + "\");";
				stmt.executeUpdate(sql);
				sql = "insert into flappybirdv2db.userlevels(userId) select userId from flappybirdv2db.users where users.userName = '" + name+ "'";
				stmt.executeUpdate(sql);
				JOptionPane.showMessageDialog(this, "User has been created successfully.", "", JOptionPane.INFORMATION_MESSAGE);
			}
			else{
				JOptionPane.showMessageDialog(this, "User has been already created. Try another username.", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			DatabaseManager.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void changePass(String name, String password){
		DatabaseManager.openConnection();
		Statement stmt = null;
		boolean user = false;
		boolean isExist = false;
		try {
			String sql = "select * from users";
			stmt = DatabaseManager.conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()){
				if(rs.getString("userName").equals(name)){
					if(rs.getString("userPassword").equals(password)){
						isExist = true;
						break;
					}
					else{
						JOptionPane.showMessageDialog(this, "Incorrect Password!", "ERROR", JOptionPane.ERROR_MESSAGE);
						user = true;
					}
				}
			}
			if(isExist){
				JLabel newPassword = new JLabel("New Password");
				
				Object[] obj = {newPassword};
				String str = JOptionPane.showInputDialog(this, obj, "PASSWORD", JOptionPane.OK_CANCEL_OPTION);
				
				if(str != null){
					String updateSql = "update flappybirdv2db.users set userPassword = '" + str + "' where userName = '" + name + "'";
					stmt.executeUpdate(updateSql);
				}
			}
			else{
				if(!user)
					JOptionPane.showMessageDialog(this, "User is not found! Try to Create an Account", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			rs.close();
			DatabaseManager.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void firePlayerEvent(SoundManager event)
	{
		Object[] listeners = listenerList.getListenerList();
		
		for ( int i = 0 ; i < listeners.length; i += 2 )
		{
			if (listeners[i] == SoundListener.class)
			{
				((SoundListener)listeners[i + 1]).playerEventOccurred(event);
			}
		}	
	}
}
